package com.xinyuan.trade.Net;

import java.util.Map;

import org.json.JSONObject;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.xinyuan.trade.R;
import com.xinyuan.trade.XYApplication;
import com.xinyuan.trade.Utils.Config;
import com.xinyuan.trade.Utils.Utils;

/**
 * volley网络访问工具类
 * 
 * @author daiy
 * 
 */
public class NetUtils {
	public interface NetCallBack {
		public void success(String json);

		public void failed(String msg);
	}

	private static RequestQueue mQueue = Volley.newRequestQueue(XYApplication
			.getContext());

	public static void getValue(Context context, String url,
			final NetCallBack callBack) {
		
		if (!Utils.isNetworkConnected(context)) {
			if (callBack != null)
				callBack.failed(context.getString(R.string.networkerror));
			return;
		}
		url = Config.HOST + url;
		
		mQueue.add(new JsonObjectRequest(Method.GET, url, null,
				new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject jsonObject) {
						if (jsonObject != null && callBack != null)
							callBack.success(jsonObject.toString());
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (callBack != null)
							callBack.failed(error.getMessage());

					}

				}));

		mQueue.start();
	}

	public static void post(Context context, String url,
			final Map<String, String> params,
			final NetCallBack callBack) {

		if (!Utils.isNetworkConnected(context)) {
			if (callBack != null)
				callBack.failed(context.getString(R.string.networkerror));
			return;
		}

		url = Config.HOST + url;
		
		StringRequest request = new StringRequest(Request.Method.POST, url,
				new Listener<String>() {

					@Override
					public void onResponse(String jsonObject) {
						if (jsonObject != null && callBack != null)
							callBack.success(jsonObject);
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (callBack != null)
							callBack.failed(error.getMessage());
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				return params;
			}
		};
		mQueue.add(request);
		mQueue.start();
	}
}
